/**
 * 设备001 发送
 */
const ecUI = require('../../../utils/ecUI.js')
const ecBLE = require('../../../utils/ecBLE.js') 
const app = getApp(); 
let that;
Page({

  /**
   * 共5条指令: 
   *  1.#time1,00:00:00:01  
   *  2.#time2,00:00:00:01  
   *  3.#mode,1   
   *  4.#reset
   *  5.#read
   * 其中1-4条, 均回复与发送是一样的.
   */
   
  data: { 
    scrollIntoView: 'scroll-view-bottom',
    receive:[],
    textRevData: '',
     modelValue:1,
     time1:{day:0,hour:0,minute:0,second:0},
     time2:{day:0,hour:0,minute:0,second:0}, 
     device:{},
     errContent:'',
     project:app.globalData.project,
    },
  onLoad(option) {
     
    // console.log(option.id)  
    // var restest='mode,0 out,0'
    // if(restest.startsWith('mode')){
    //   var modelValue=restest.substring(5,6)
    //   var modelValueNew=(parseInt(modelValue)+1)
    //   restest=restest.replace('mode,'+modelValue,'mode,'+modelValueNew)
    //   console.log(restest)
    // }
    that=this;
    var deviceList=wx.getStorageSync('deviceList') 
    console.log(deviceList)
    if(deviceList){
      deviceList.forEach(item=>{
        if(item.deviceId==option.id){
          this.data.device=item;
        }
      })
      wx.setNavigationBarTitle({
        title:that.data.device.deviceName+'设置'
      });  
    } 
     
    //调试接收数据样式
    this.debugRecv()


    // that=this;
    //设置字符集格式
    ecBLE.setChineseType(ecBLE.ECBLEChineseTypeGBK)
    //on disconnect
     this.connectChange();
     this.receiveData(); 
  },
  // 调试用
  debugRecv(){ 
    console.log(2212)
    setTimeout(function() {
      console.log(12)
      var  receive=[{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'},{data:'1',time:'1111'}];
      var textData='';
      receive.forEach(item=>{
         textData+=item.time+'   '+item.data+ '\r\n'
      })
      that.setData({ 
        textRevData: textData
      })
      that.scrollToBottom();
    }, 1000); // 500毫秒后执行
  },
  scrollToBottom() {
    if (that.data.scrollIntoView === "scroll-view-bottom") {
      that.setData({ scrollIntoView: "scroll-view-bottom2" })
  } else {
    that.setData({ scrollIntoView: "scroll-view-bottom" })
  }
     
  },
  //清除接收信息
  clearReceveTab(){
     that.setData({
       receive:[],
      textRevData:''
     })
  },
  //重启定时器
  resetTab(){ 
    var resetData='#reset'
    that.sendData(resetData);
  },
  //从定时器读取
  getTab(){
    var readData='#read'
    that.sendData(readData);
  },
  //保存到定时器
 sendTab(){  
     var modelData=that.getModelData(that.data.modelValue); 
     var time1Data=that.getTimeData(that.data.time1,1);
     var time2Data=that.getTimeData(that.data.time2,2); 
     that.sendData(modelData);//实际发送是要0-3
      setTimeout(function() {
        that.sendData(time1Data);
        setTimeout(function() {
          that.sendData(time2Data);
        }, 500); // 500毫秒后执行
      }, 500); // 500毫秒后执行  
 
  },
  sendMoel(){
    var p = new Promise(function(resolve,reject){
      　　 var modelData=that.getModelData(that.data.modelValue); 
          that.sendData(modelData);
          })
      return p
  },
  refresh(){
    Number(time1.day) 
  },
  getModelData(value){ 
    var resdata='#mode,' 
    resdata+=value-1;
    return resdata
  },
  getTimeData(timeobj,index){ 
    // console.log('getTimeDAta');
     var resdata='#time'+index+',' 
     const time = Object.assign({}, timeobj); 
     time.day = time.day < 10 ? '0' + time.day : time.day
     time.hour = time.hour < 10 ? '0' + time.hour : time.hour
     time.minute = time.minute < 10 ? '0' + time.minute : time.minute
     time.second = time.second < 10 ? '0' + time.second : time.second
     resdata+=time.day+':'+time.hour+':'+time.minute+':'+time.second
     return resdata;
  },
  sendData(senddata){ 
      if (senddata.length === 0) {
          ecUI.showModal('提示', '请输入要发送的数据')
          return
      }
      let tempSendData = senddata.replace(/\n/g, '\r\n')
      if (tempSendData.length > 244) {
          ecUI.showModal('提示', '最多只能发送244字节')
          writeBLECharacteristicValue
      }
      console.log('发送:')
      console.log(tempSendData)
      ecBLE.writeBLECharacteristicValue(tempSendData, false)  
  },
  connectChange(){
        ecBLE.onBLEConnectionStateChange(() => {
          ecUI.showModal('提示', '设备断开连接')
      })
  },
  receiveData(){
    ecBLE.onBLECharacteristicValueChange((str, strHex) => {  
          if(str.startsWith('mode')||str.startsWith('#mode')){
            var index=str.indexOf('mode')
            console.log('接收到的mode值：'+str)
            var modelValue=str.substring(5+index,6+index)
            var modelValueNew=(parseInt(modelValue)+1)
            str=str.replace('mode,'+modelValue,'mode,'+modelValueNew)
            console.log('处理后的mode值：'+str)
          } 
        var receiveData={
          data:str,
          time:that.dateFormat('[hh:mm:ss,S]:', new Date())
        } 
        console.log('接收:');
        console.log(receiveData);
        that.data.receive.push(receiveData);
        console.log(that.data.receive);
        var textData='';
        that.data.receive.forEach(item=>{
           textData+=item.time+'   '+item.data+ '\r\n'
        })
       that.setData({
        //  receive: that.data.receive
        textRevData:textData
       })
       that.scrollToBottom();
     })
  },
  getModel(e){  
    let value = Number(e.detail.value); // 获取输入值并转换为数字 
    console.log(value)
    if(value>=11&&value<=14){
      value=value-10;
    }
    let min=e.currentTarget.dataset.min;
    let max=e.currentTarget.dataset.max;
    if (!Number.isFinite(value)) { // 如果输入的不是数字，可以重置或给出提示 
      value=e.detail.value.replace(/[^0-9]/g,'')
      this.setData({ modelValue: value }); // 重置输入值
      return;
    } 
    if (value > max) { // 如果输入值大于最大值，重置或提示
      this.setData({ modelValue: max}); // 设置最大值或给出提示
    }else if(value<min){ 
      this.setData({ modelValue: min}); // 设置最大值或给出提示
    }else {
      this.setData({ modelValue: value}); // 设置最大值或给出提示
    }  

 },
 getTime1(e){
  let value = Number(e.detail.value); // 获取输入值并转换为数字  
  let type=e.currentTarget.dataset.type;
  let min=e.currentTarget.dataset.min;
  let max=e.currentTarget.dataset.max; 
  if (!Number.isFinite(value)) { // 如果输入的不是数字，可以重置或给出提示
    value= e.detail.value.replace(/[^0-9]/g,'')
    // value=min; 
  } 
  if (value > max) { // 如果输入值大于最大值，重置或提示
    value=max;
  }   
  var time=this.data.time1;
  // time.day=Number(time.day)
  // time.hour=Number(time.hour)
  // time.minute=Number(time.minute)
  // time.second=Number(time.second)
  if(type=="day"){time.day=value;}
  if(type=="hour"){time.hour=value;}
  if(type=="minute"){time.minute=value;}
  if(type=="second"){time.second=value;}
  this.setData({
    time1:time
  })
 },
 getTime2(e){
  let value = Number(e.detail.value); // 获取输入值并转换为数字 
  let type=e.currentTarget.dataset.type;
  let min=e.currentTarget.dataset.min;
  let max=e.currentTarget.dataset.max; 
  if (!Number.isFinite(value)) { // 如果输入的不是数字，可以重置或给出提示
    value= e.detail.value.replace(/[^0-9]/g,'')
    // value=min; 
  } 
  if (value > max) { // 如果输入值大于最大值，重置或提示
    value=max;
  }    
  var time=this.data.time2;
  // time.day=Number(time.day)
  // time.hour=Number(time.hour)
  // time.minute=Number(time.minute)
  // time.second=Number(time.second)
  if(type=="day"){time.day=value;}
  if(type=="hour"){time.hour=value;}
  if(type=="minute"){time.minute=value;}
  if(type=="second"){time.second=value;}
  this.setData({
    time2:time
  })
 },
 clearInput(e){
   if(e.currentTarget.dataset.obj=="mode"){ 
       this.setData({
        modelValue:1
       }) 
   }else{
      let obj=e.currentTarget.dataset.obj.split(',');
      let timer=obj[0]
      let type=obj[1]
      console.log(timer,type);
      var time=this.data.time1; 
      if(timer=="time2"){
        time=this.data.time2; 
      }
      if(type=="day"){time.day=0;}
      if(type=="hour"){time.hour=0;}
      if(type=="minute"){time.minute=0;}
      if(type=="second"){time.second=0;}
      if(timer=="time1"){
        this.setData({
          time1:time
        })
      }else{
        this.setData({
          time2:time
        })
        }
      
  }   
 },
 btClearTap() {
  this.setData({ receiv: [] })
},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
      ecBLE.onBLEConnectionStateChange(() => { })
      ecBLE.onBLECharacteristicValueChange(() => { })
      ecBLE.closeBLEConnection()
  },
 dateFormat(fmt, date) {
  let o = {
      'M+': date.getMonth() + 1, //月份
      'd+': date.getDate(), //日
      'h+': date.getHours(), //小时
      'm+': date.getMinutes(), //分
      's+': date.getSeconds(), //秒
      'q+': Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒
  }
  if (/(y+)/.test(fmt))
      fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
  for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt)) {
          // console.log(RegExp.$1.length)
          // console.log(o[k])
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                  ? (o[k] + '').padStart(3, '0')
                  : ('00' + o[k]).substr(('' + o[k]).length)
          )
      }
  return fmt
},
})